<script lang="ts" setup>
import type { ItemType, MenuProps } from 'ant-design-vue';

import { onMounted, reactive, ref } from 'vue';

import { getChapterOfBook, loadContentByChapterId } from '#/api/core/books';
import {
  type ChapterQueryRequest,
  type PageChapterVo,
  type SectionVo,
} from '#/api/types';

const props = defineProps<{
  bookId: number;
  title: string;
}>();
const selectedKeys = ref<string[]>(['1']);
const openKeys = ref<string[]>(['sub1']);

const bookId = ref(props.bookId);
const title = ref(props.title);

interface Content {
  content: string;
  title: string;
}

const contents = ref<Content[]>([]);

const chapterParams = ref<ChapterQueryRequest>({
  bookId: bookId.value,
  current: 1,
  pageSize: 100,
  sortField: 'chapter_number',
});

function getItem(
  label: string,
  key: number,
  children?: ItemType[],
  type?: 'group',
): ItemType {
  return {
    key,
    label,
    type,
    children,
  } as ItemType;
}

// 使用 reactive 创建响应式数组
const chapterItems = reactive<ItemType[]>([]);
const items = reactive<ItemType[]>([
  getItem(title.value, bookId.value, chapterItems),
]);

// 页面打开自动获取书籍的章节，显示在目录中
onMounted(async () => {
  try {
    const result: PageChapterVo = await getChapterOfBook(chapterParams.value);
    const chapterVOs = result.records;

    if (chapterVOs && chapterVOs.length > 0) {
      for (const chapterVO of chapterVOs) {
        chapterItems.push(getItem(chapterVO.title, chapterVO.chapterId));
      }
    }
  } catch (error) {
    console.error('获取章节失败:', error);
  }
});

const loadChapterContent = async (chapterId: number) => {
  // 初始化请求参数
  const contentQueryParam = {
    chapterId,
  };

  try {
    // 更新当前章节内容
    const result = await loadContentByChapterId(contentQueryParam);
    const sections: SectionVo[] = result.sections || []; // 获取 sections

    contents.value = [];
    // 解构获取每个 section 的 sectionId 和 title
    // 循环将结构出来的数据放到 contents 数组中
    sections.forEach(({ content = '', title = '' }) => {
      contents.value.push({ content, title });
    });
  } catch (error) {
    console.error('加载章节内容失败:', error);
    // 处理加载章节失败的情况（例如，显示错误信息）
    contents.value.push({ content: '无法加载章节内容。', title: '加载失败' });
  }
};

const handleClick: MenuProps['onClick'] = (e) => {
  const chapterId = e.key; // 获取点击的章节 ID
  loadChapterContent(Number(chapterId)); // 加载章节内容
};
</script>
<template>
  <div class="layout">
    <a-menu
      v-model:open-keys="openKeys"
      v-model:selected-keys="selectedKeys"
      :items="items"
      class="menu"
      mode="inline"
      @click="handleClick"
    />
    <div class="content-area">
      <template v-if="contents">
        <article
          v-for="(content, index) in contents"
          :key="index"
          class="content-item"
        >
          <h3 class="content-title">{{ content.title }}</h3>
          <p class="content-text">{{ content.content }}</p>
        </article>
      </template>
      <template v-else>
        <p class="empty-message">章节内容为空。</p>
      </template>
    </div>
  </div>
</template>
<style scoped>
.layout {
  display: flex;
}

.menu {
  position: fixed;
  width: 13%;
  height: 100vh; /* 设置高度为视口高度 */
  overflow-y: auto; /* 如果内容超出则出现滚动条 */
  border-right: 1px solid #ddd; /* 边框分隔 */
}

.content-area {
  padding: 20px;
  margin-left: 15%; /* 给右侧内容留出空间 */
}

.content-item {
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}

.content-title {
  font-size: 1.5em;
  margin: 0 0 10px;
}

.content-text {
  font-size: 1em;
  line-height: 2;
  flex: auto;
}

.empty-message {
  font-style: italic;
}
</style>
